package com.supcalls.tool;

import java.util.concurrent.*;

/**
 * Semaphore 用于控制同时访问某些资源的线程数量。
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);  // Allow 2 threads to access the resource simultaneously

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            new Thread(() -> {
                try {
                    semaphore.acquire();  // Acquire a permit
                    System.out.println("Task " + taskId + " is accessing the resource.");
                    Thread.sleep(2000);
                    System.out.println("Task " + taskId + " is releasing the resource.");
                    semaphore.release();  // Release the permit
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
